//
//  LoginViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 16/1/22.
//  Copyright © 2016年 李萍. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import SwiftKeychainWrapper

class LoginViewController: UIViewController {
    @IBOutlet weak var accountTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        let userDefaults = NSUserDefaults.standardUserDefaults()
        var account = userDefaults.valueForKey("email") as? String
        if account == nil {
            account = ""
        }
        let password = KeychainWrapper.stringForKey(account!)
        
        if account!.isEmpty {
            accountTextField.text = account
            passwordTextField.text = password
        } else {
            accountTextField.text = ""
            passwordTextField.text = ""
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func fetchForLogin() -> Void {
        Alamofire.Manager.sharedInstance.request(Method.POST,
                                                 GITAPI_HTTPS_PREFIX+GITAPI_SESSION,
                                                 parameters: ["email"    : (accountTextField.text)!,
                                                              "password" : (passwordTextField.text)!]
            ).responseJSON {
            response in
            if let results = response.result.value {
                let jsonArray = JSON(results)
                if jsonArray.count > 0 {
                    let user = GTUser(json: jsonArray)
                    let userinfos = UserInfos()
                    
                    userinfos.saveUserInfos(user)
                    userinfos.saveLoginPassword(self.accountTextField.text!, password:self.passwordTextField.text!)
                    
                    self.dismissViewControllerAnimated(true, completion: nil)
                } else {
                    print("登录失败！")
                }
                
            }
        }
    }
    @IBAction func Login(sender: AnyObject) {
        self.fetchForLogin()
    }
}
